package com.tibbytang.opengllearn.util

import android.opengl.GLES20
import android.util.Log

private const val TAG = "ES20_ERROR"

object ShaderUtil {

    fun createProgram(vertexShaderSource: String, fragmentShaderSource: String): Int {
        // 加载定点着色器
        val vShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderSource)
        if (vShader == 0) {
            Log.e(TAG, "加载顶点着色器失败")
            return 0
        }
        val fShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderSource)
        if (fShader == 0) {
            Log.e(TAG, "加载片元着色器失败")
            return 0
        }
        val program = GLES20.glCreateProgram()
        if (program != 0) {
            GLES20.glAttachShader(program, vShader)
            checkError("vShader AttachShader")
            GLES20.glAttachShader(program, fShader)
            checkError("fShader AttachShader")
            GLES20.glLinkProgram(program)
            val linkStatus = intArrayOf(1)
            GLES20.glGetShaderiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0)
            if (linkStatus[0] != GLES20.GL_TRUE) {
                GLES20.glDeleteProgram(program)
                Log.e(TAG, "链接程序失败")
                checkError("createProgram")
                Log.e(TAG, "${GLES20.glGetShaderInfoLog(program)}")
            }
        } else {
            Log.e(TAG, "创建程序失败")
        }
        return program
    }

    private fun loadShader(shaderType: Int, shaderSource: String): Int {
        val shader = GLES20.glCreateShader(shaderType)
        if (shader != 0) {
            GLES20.glShaderSource(shader, shaderSource)
            GLES20.glCompileShader(shader)
            val vexCompiled = intArrayOf(1)
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, vexCompiled, 0)
            if (vexCompiled[0] == 0) {
                GLES20.glDeleteShader(shader)
                Log.e(TAG, " Could not comiple shader $shaderType ")
                Log.e(TAG, " ${GLES20.glGetShaderInfoLog(shader)}")
            }
        } else {
            Log.e(
                TAG,
                " Could not create shader ${GLES20.GL_VERTEX_SHADER} :Error $shaderType "
            )
        }
        return shader
    }

    private fun checkError(name: String) {
        val error: Int = GLES20.glGetError()
        if (error != GLES20.GL_NO_ERROR) {
            Log.e(TAG, "$name :glError $error")
        }
    }
}